import Vue from 'vue'
import VueRouter from 'vue-router'
import { getUserByTokenApi } from '@/request/httpApi'
import { SETMENU } from '@/store/nutation-types'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('../views/login/Login.vue')
  },
  /* {
    path: '/',
    name: 'Index',
    component: () => import('../views/Index.vue'), children: [
      {
        path: "/good",
        component: () => import('../views/good/Good.vue'),
      },
      {
        path: "/attribute",
        component: () => import('../views/attribute/Attribute.vue'),
      }
    ]
  } */
]
const routesArr = {
  "/good": {
    path: "/good",
    component: () => import('../views/good/Good.vue'),
  },
  "/attribute": {
    path: "/attribute",
    component: () => import('../views/attribute/Attribute.vue'),
  },
  "/category": {
    path: "/category",
    component: () => import('../views/category/Category.vue'),
  },
  "/brand": {
    path: "/brand",
    component: () => import('../views/brand/Brand.vue'),
  },
  "/addbrand": {
    path: "/addbrand",
    component: () => import('../views/addbrand/Addbrand.vue'),
  },
  "/editbrand": {
    path: "/editbrand",
    component: () => import('../views/editbrand/Editbrand.vue'),
  },
  "/addattribute": {
    path: "/addattribute",
    component: () => import('../views/addattribute/AddAttribute.vue'),
  },
  "/editattribute": {
    path: "/editattribute",
    component: () => import('../views/editattribute/Editattribute.vue'),
  },
}

const router = new VueRouter({
  routes
})

const generateRoute = () => {
  let newRoutes = []
  // 把登录后的权限菜单列表和路由进行对比，得到用户路规则，动态添加
  for (let i = 0; i < store.state.menu.length; i++) {
    let path = store.state.menu[i].path
    if (routesArr[path]) {
      newRoutes.push(routesArr[path])
    }
  }
  console.log(newRoutes);
  router.addRoutes([
    {
      path: '/',
      component: () => import(/**/"../views/homepage/Homepage.vue"), children: newRoutes
    }
  ])
}



// 路由前置守卫
router.beforeEach((to, from, next) => {
  console.log(to, from);
  const token = localStorage.getItem("token")
  // const userinfo = store.state.userinfo
  // if (token && !userinfo) {
  if (token && store.state.menu.length === 0) {
    // 发送请求获取用户权限列表
    getUserByTokenApi().then(res => {
      if (res.errno === 0) {
        // 设置vuex权限列表
        store.commit(SETMENU, res.data.menu)
        generateRoute()

        console.log(123);
        // console.log(store.state.menu);
        // console.log(store.state.menu[0].path);
      }
      // store.dispatch("getUserInfo")
      console.log(123);
      next(to.path)
      console.log(123);
    })
  } else if (token && store.state.menu.length > 0 && from.path === "/login" && to.path === "/") {
    generateRoute()
    console.log(456);
    next(store.state.menu[0].path)
  } else if (!token && to.path !== "/login") {
    next('/login')
  } else {
    next()
  }
})

export default router
